package ru.royalgatemagazine.app.http;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;

import ru.royalgatemagazine.app.Debug;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.util.Log;

public class HttpSimpleClient{
		
//	public static final String API = "http://101.kenigart.ru/";
	public static final String API = "http://101.royalgatemagazine.ru/";
	public static final String PIC_PATH = API + "imglabels/";
	public static final String API_PHP = API + "published/api.php";
	public static final String MAP_LINK_PATTENR = API_PHP + "?act=showmagazinemap&mid=%d";//TODO refactoring unsafe!!!
	public static final String PAGE_LINK_PATTENR = API_PHP + "?act=showmagazinepage&mid=%d&page=%d";//TODO refactoring unsafe!!!
	
	public HttpSimpleClient(Context context){
		this.context = context;
		this.apiAdress = API_PHP;
	}
	
	private final int TIMEOUT_CONN_MILLISEC = 30000;
	private final int TIMEOUT_READ_MILLISEC = 30000;
	private final String apiAdress;
	private final Context context;
	private int errorCode = ErrorCode.OK;
	private final String EMPTY_STRING = "";
	
	/**
	 *	Add your data this way:			
	 *	List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
	 *	nameValuePairs.add(new BasicNameValuePair("id", "12345"));
	 *	nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!"));
	*/
	
	public Bitmap loadBitmap(String url){
		
		ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		boolean mobileConnected = manager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).isConnected();
		boolean wifiConnected = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnected();
		
		if(!(mobileConnected || wifiConnected)){
			errorCode = ErrorCode.NO_NETWORK;
			Debug.log("HttpSimpleClient.loadBitmap():errorCode = ErrorCode.NO_NETWORK");
			return null;
		}
		
		try {
			InputStream is = (InputStream) new URL(url).getContent();
			return BitmapFactory.decodeStream(is);
		} catch (Exception e) {
			Debug.log("HttpSimpleClient.loadBitmap():Exception:"+e.toString());
			return null;
		}
	}
	
	public Bitmap getBitmap(List<NameValuePair> nameValuePairs){
		ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		boolean mobileConnected = manager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).isConnected();
		boolean wifiConnected = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnected();
		
		if(!(mobileConnected || wifiConnected)){
			errorCode = ErrorCode.NO_NETWORK;
			return null;
		}
		
		HttpClient httpClient = new DefaultHttpClient();
		httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, TIMEOUT_CONN_MILLISEC);
		httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, TIMEOUT_READ_MILLISEC);
		HttpPost httppost = new HttpPost(apiAdress);
		
		try {
			UrlEncodedFormEntity urlEncFormEnt = new UrlEncodedFormEntity(nameValuePairs,"UTF-8");
			httppost.setEntity(  urlEncFormEnt  );
			HttpResponse response = httpClient.execute(httppost);
			int status = response.getStatusLine().getStatusCode();
			if (status != HttpStatus.SC_OK) {
				return null;
			}
			InputStream is = response.getEntity().getContent();
			if(is!=null){
				return BitmapFactory.decodeStream(is);
			}
		} catch (Exception e) {
			Debug.log("HttpSimpleClient.getBitmap():Exception:"+e.toString());
			return null;
		}
		return null;
	}
	
	public String getContent(List<NameValuePair> nameValuePairs){
		
		ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		boolean mobileConnected = manager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).isConnected();
		boolean wifiConnected = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnected();
		
		if(!(mobileConnected || wifiConnected)){
			errorCode = ErrorCode.NO_NETWORK;
			return EMPTY_STRING;
		}
		
		HttpClient httpClient = new DefaultHttpClient();
		httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, TIMEOUT_CONN_MILLISEC);
		httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, TIMEOUT_READ_MILLISEC);
		HttpPost httppost = new HttpPost(apiAdress);
		try{
			UrlEncodedFormEntity urlEncFormEnt = new UrlEncodedFormEntity(nameValuePairs,"UTF-8");
		    httppost.setEntity(  urlEncFormEnt  );
		    HttpResponse response = httpClient.execute(httppost);
		    int status = response.getStatusLine().getStatusCode();
			if (status != HttpStatus.SC_OK) {//BAD
				errorCode = ErrorCode.SERVICE_UNAVAILABLE;
				switch(status){
				case HttpStatus.SC_REQUEST_TIMEOUT:
					errorCode = ErrorCode.LOW_CONNECTION;
					break;
				case HttpStatus.SC_SERVICE_UNAVAILABLE:
					errorCode = ErrorCode.SERVICE_UNAVAILABLE;
					break;
				default:
					errorCode = ErrorCode.SERVICE_UNAVAILABLE;
					Log.e("TEXTA", "ERROR HttpStatus = " + status);
				}
				return EMPTY_STRING;
			} else {//GOOD
				String answer = ResponseHandling(response.getEntity());
				if(answer!=null && answer.length()>0){//GOOD
					errorCode = ErrorCode.OK;
					return answer;
				}
				else{//BAD
					answer = EMPTY_STRING;
					errorCode = ErrorCode.SERVICE_UNAVAILABLE;
					return answer;
				}
			}
         }
         catch (Exception e){//THROWS ResponseHandling(HttpEntity entity)
        	 errorCode = ErrorCode.SERVICE_UNAVAILABLE;
        	 return EMPTY_STRING;
         }
         finally {
 			if (httpClient != null) {
 				httpClient.getConnectionManager().shutdown();
 			}
         }
	}
	
	private String ResponseHandling(HttpEntity entity) throws IllegalStateException, IOException {
		if (entity != null) {
			InputStream inputStream = null;
			try {
				inputStream = entity.getContent(); 

				BufferedReader bufferReader = null;
				bufferReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 4096);
				String inputLine = "";
				StringBuilder content = new StringBuilder("");
				while ((inputLine = bufferReader.readLine()) != null) {
					content.append(inputLine);
					content.append('\n');
				}
				return content.toString();
	    	
			} finally {
				if (inputStream != null) {
					inputStream.close(); 
				}
			}
		}
		else{
			errorCode = ErrorCode.SERVICE_UNAVAILABLE;
			return EMPTY_STRING;
		}
	}

	public int getErrorCode() {
		return errorCode;
	}
	
	public static class ErrorCode {
		
		public static final int OK = 0;
		public static final int NO_NETWORK = 1;
		public static final int LOW_CONNECTION = 2;
		public static final int SERVICE_UNAVAILABLE = 3;
		public static final int UNKNOWN = 4;
		
	}
}